package cc.rengu.igas.mcps.core.service.trans.common;


import cc.rengu.igas.channel.cups.common.constant.CupsConfigConstant;
import cc.rengu.igas.mcps.common.constant.McpsTreeNodeConstant;
import cc.rengu.igas.mcps.common.dao.TermTxnMapper;
import cc.rengu.igas.mcps.common.dao.impl.TermTxnMapperImpl;
import cc.rengu.igas.mcps.common.entity.TermTxn;
import cc.rengu.igas.mcps.common.enums.AcctTypeEnum;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.service.base.ManageService;
import cc.rengu.igas.mcps.facade.bean.TransInfo;
import cc.rengu.igas.mcps.facade.request.PosBatchSendRequest;
import cc.rengu.igas.mcps.facade.response.PosBatchSendResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.BinInfo;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.BinInfoService;
import cc.rengu.oltp.service.realize.impl.BinInfoServiceImpl;
import cc.rengu.oltp.utility.util.*;

import java.util.List;

/**
 * POSC发起批上送交易请求 M00MC004
 */
public class PosBatchSendService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        PosBatchSendRequest posBatchSendReq = new PosBatchSendRequest();
        ConvertUtil.convertOutput(posBatchSendReq);
        return posBatchSendReq;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        PosBatchSendRequest posBatchSendReq = (PosBatchSendRequest) request;
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        List<TransInfo> transInfoList = posBatchSendReq.getTransInfoList();

        TermTxnMapper termTxnMapper = new TermTxnMapperImpl();
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        for (TransInfo transInfo : transInfoList) {
            TermTxn termTxn = new TermTxn();
            initTermTxnDetail(termTxn, transInfo);
            int iRetCode = termTxnMapper.insertTermTxn(termTxn);
            if (iRetCode != 0) {
                rglog.error("插入终端交易流水表失败，retCode<{}>", iRetCode);
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.INSERT_DATA_ERROR.getRespCode(), RespCodeEnum.INSERT_DATA_ERROR.getRespDesc());
            }
        }
        /* 结束数据库事务 */
        dbsUtil.dbsEndTransaction(true);

        /* 重组响应结果 */
        PosBatchSendResponse posBatchSendRsp = new PosBatchSendResponse();
        ConvertUtil.convertOutput(posBatchSendRsp);
        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(posBatchSendRsp);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        PosBatchSendResponse posBatchSendRsp = (PosBatchSendResponse) bizResponse.getResult();
        ConvertUtil.convertInput(posBatchSendRsp);
    }

    private void initTermTxnDetail(TermTxn termTxn, TransInfo transInfo) throws Exception {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        /* 交易日期 */
        if (null == termTxn.getTxnDate()) {
            termTxn.setTxnDate(DateUtil.getCurrentDate());
        }
        /* 交易时间 */
        if (null == termTxn.getTxnTime()) {
            termTxn.setTxnTime(DateUtil.getCurrentTime());
        }

        /* 机构标识 */
        if (null == termTxn.getInstId()) {
            termTxn.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        }

        /* 交易流水号 */
        if (null == termTxn.getFrontSeqNum()) {
            termTxn.setFrontSeqNum(transInfo.getTermSsn());  //终端流水号
        }

        /* 交易类型 */
        if (null == termTxn.getTxnNum()) {
            termTxn.setTxnNum(transInfo.getOriTxnNum());
        }

        /* 支付账号 */
        if (null == termTxn.getPayerAcctNo()) {
            termTxn.setPayerAcctNo(transInfo.getPayAcctNo());
        }

        /* 交易币种 */
        if (null == termTxn.getTransCcy()) {
            termTxn.setTransCcy(transInfo.getTransCcy());
        }

        /* 交易金额 */
        termTxn.setTransAmt(transInfo.getTransAmt());

        /* 系统参考号 */
        if (null == termTxn.getReferenceNo()) {
            termTxn.setReferenceNo(transInfo.getReferenceNo());
        }

        /* 终端号 */
        if (null == termTxn.getTermNo()) {
            termTxn.setTermNo(xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.TERM_NO));
        }

        /* 商户号 */
        if (null == termTxn.getMchntNo()) {
            termTxn.setMchntNo(xmlTreeUtil.getXmlTreeStringValue(McpsTreeNodeConstant.MCHNT_NO));
        }

        /* 本行/他行 标识 */
        String fwdInstCode = XmlConfigUtil.getXmlConfigCacheKeyValue(CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_FWD_INS_CODE);
        if (null != fwdInstCode && fwdInstCode.substring(0, 4).equals(transInfo.getPayAcctNo().substring(0, 4))) {
            //本行
            termTxn.setIssuerType("0");   //本行卡-0
        } else {
            termTxn.setIssuerType("1");  //他行卡-1
        }

        /* 获取账户类型 */
        BinInfoService binInfoService = new BinInfoServiceImpl();
        BinInfo binInfo = binInfoService.getCardBinInfo(termTxn.getPayerAcctNo());
        if (null == binInfo) {
            rglog.error("无法找到卡号:<{}>对应的卡BIN信息!", transInfo.getPayAcctNo());
        } else {
            //账户类型
            switch (binInfo.getCardType()) {
                case "1":
                    termTxn.setPayAcctType(AcctTypeEnum.DEBIT.getAcctType());
                case "2":
                    termTxn.setPayAcctType(AcctTypeEnum.CREDIT.getAcctType());
                case "3":
                    termTxn.setPayAcctType(AcctTypeEnum.QCREDIT.getAcctType());
                case "4":
                    termTxn.setPayAcctType(AcctTypeEnum.PRECARD.getAcctType());
                default:
                    termTxn.setPayAcctType(AcctTypeEnum.DEFAULT.getAcctType());
            }
        }

        /* 初始化设置 */
        termTxn.setCreateTime(DateUtil.getCurrentDateTime("yyyyMMddHHmmss"));
    }
}
